--#include "data\functions\Activity\OpenServer\OpenServerCommon.lua" once
--#include "data\config\item\SwingEquip.lua" once
--#include "data\config\misc\MeridianConfig.lua" once
--开服全民竞技

--[[    // 1升级,2翅膀,3符文,4灵珠 5 特戒 6 武魂 7 经络 8 注灵 9 武魂 10 vip
enOpenServerRank_Leveling  
enOpenServerRank_Swing
enOpenServerRank_HeroRune
enOpenServerRank_SoulBall
enOpenServerRank_SpecialRing
enOpenServerRank_Wuhun
enOpenServerRank_Merdian
enOpenServerRank_Inject
enOpenServerRank_Diamond
enOpenServerRank_VIP
]]



--[开服活动]请求开服活动数据
function SendOpenServerPKRankData( sysarg, packet )
    --[[
	local nId = DataPack.readByte( packet )

	if not IsInOpenServerDay() then
		return
	end

	if nId >= enOpenServerRank_Leveling and nId <=enOpenServerRank_VIP then
		SendOpenServerPKRankDataById(sysarg, nId)
	end
    ]]
end


--根据id获取配置或者变量
function OpenServerPKRankGetSendCount(nId)
	local sVar = System.getStaticVar()
	if not sVar.openServerPKRankSendAwardCount then
		sVar.openServerPKRankSendAwardCount = {}
	end
	if not sVar.openServerPKRankSendAwardCount[nId] then
		sVar.openServerPKRankSendAwardCount[nId] = {}
	end
	return sVar.openServerPKRankSendAwardCount[nId]
end


--领取开服活动奖励
function OpenServerPKRankGetAward(sysarg, packet)
    --[[
	local nId = DataPack.readByte( packet )
	local actCfg = OpenServerCfg.pkRankData[nId]

	if not actCfg then
		return
	end
	
	if not IsInOpenServerDay() then
		return
	end

	local Index = DataPack.readByte(packet)

	local nOpenServerDay = System.getDaysSinceOpenServer()
	if actCfg.openDay and nOpenServerDay < actCfg.openDay then --未到开启天数，不能领奖励	
		return
	end

	if actCfg.endDay and nOpenServerDay > actCfg.endDay then --超过开启天数，不能领奖励	
		return
	end

	local subAwards = actCfg.Rewards
	if not subAwards  then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.OpenServer021, ttFlyTip)
		return
	end

	if Index > #subAwards then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.OpenServer021, ttFlyTip)
		return
	end

	local curAwards = subAwards[Index]

	if not curAwards then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.OpenServer021, ttFlyTip)
		return
	end

	if not curAwards.awards then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.OpenServer021, ttFlyTip)
		return
	end

	local actorid = Actor.getActorId(sysarg)
	local data = gRankMgr_GetValueById(actorid, actCfg.RankId, 1)

    local myData = BaseFuc_unserialize(data)

    if not myData then
        myData = {}
    end

    if not myData.myAwardState then
    	myData.myAwardState = {}
    end

    if myData.myAwardState and type(myData.myAwardState) == "number" then
    	myData.myAwardState = {}
    end

    if not myData.sex then
        myData.sex = Actor.getIntProperty(sysarg, PROP_ACTOR_SEX)
        myData.vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
    end

    local sVarSendNum = OpenServerPKRankGetSendCount(nId)
    local hadSendCount = sVarSendNum[Index] or 0
    
    if curAwards.limitNum ~= -1 and curAwards.limitNum <= hadSendCount then
    	Actor.sendTipmsg(sysarg, Lang.ScriptTips.OpenServer006, ttFlyTip)
    	return
	elseif myData.myAwardState[Index] and myData.myAwardState[Index] == OpenServerAwardState_Complete_No_Award then --可以领
		if not Awards.CheckBagGridCount(sysarg, curAwards.awards) then
			Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0015, ttFlyTip)
			return
		end
		hadSendCount = hadSendCount + 1
		sVarSendNum[Index] = hadSendCount
		myData.myAwardState[Index] = OpenServerAwardState_Complete_Had_Award
		local newData = BaseFuc_serialize(myData)
    	gRankMgr_SetRankEx(actorid, actCfg.RankId, 1, newData)

		Awards.Give(sysarg,curAwards.awards,1096,Lang.LogTips.OpenServerPKRank)
		if curAwards.limitNum > 0 then
			OpenServerPKRankBroadMsg(Actor.getActorId(sysarg), Actor.getName(sysarg), actCfg)
		end
		SendOpenServerPKRankDataById(sysarg, nId)
	end
    ]]
end

function OpenServerPKRankTriggleEvent(sysarg, nId, param1, param2) -- 当不是等级竞技的时候circle无用为0
    --[[
	if nId >= enOpenServerRank_Leveling and nId <=enOpenServerRank_VIP then
		OnOpenServerPKRankHandler(sysarg, nId, param1, param2)	
	end
    ]]
end
	

function OnOpenServerPKRankHandler(sysarg, nId, param1, param2)
    if not IsInOpenServerDay() then
        return
    end
    local actCfg = OpenServerCfg.pkRankData[nId]
    if not actCfg then
        return
    end

    local actOpenDay = actCfg.openDay or 1
    local actEndDay = actCfg.endDay or OpenServerCfg.OpenServerDay
    local nOpenServerDay = System.getDaysSinceOpenServer()

    if nOpenServerDay > actEndDay then
        return
    end

    local actorid = Actor.getActorId(sysarg)
    if not param2 then
        param2 = 0
    end
    if not param1 then
        param1 = 0
    end

    local oldValue = gRankMgr_GetValue(actorid, actCfg.RankId)

    if enOpenServerRank_Inject == nId then  --注灵值特殊处理
        param1 = param1 + oldValue
    end

    local value = param1 + param2 * OpenServerCfg.OpenServerCircleRate

    if enOpenServerRank_VIP == nId then --vip特殊处理
        value = param1 * OpenServerCfg.OpenServerVIPRate + param2
    end

    if value < oldValue then
        return
    end

    local getMyOldRank = GetOpenServerPKRankMyRank(actorid, nId, param1, param2)

    gRankMgr_SetRank(actorid, actCfg.RankId, value)

    local getMyNewRank = GetOpenServerPKRankMyRank(actorid, nId, param1, param2)

    local data = gRankMgr_GetValueById(actorid, actCfg.RankId, 1)

    local myData = BaseFuc_unserialize(data)

    if not myData then
        myData = {}
    end

    if not myData.myAwardState then
        myData.myAwardState = {}
    end

    if myData.myAwardState and type(myData.myAwardState) == "number" then
        myData.myAwardState = {}
    end

    if not myData.sex then
        myData.sex = Actor.getIntProperty(sysarg, PROP_ACTOR_SEX)
        myData.vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
    end
        
    local sendData = false
    for iii, v in ipairs(actCfg.Rewards) do
        if param1 >= v.param and param2 >= (v.exparam or 0) then
            local awardState = myData.myAwardState[iii] or OpenServerAwardState_No_Complete
            if awardState == OpenServerAwardState_No_Complete then --还未完成
                myData.myAwardState[iii] = OpenServerAwardState_Complete_No_Award
                if nOpenServerDay >= actOpenDay then
                    sendData = true
                end
            end
        end
    end
    

    local newData = BaseFuc_serialize(myData)
    gRankMgr_SetRankEx(actorid, actCfg.RankId, 1, newData)

    local setState = false
    if getMyNewRank ~= getMyOldRank and nOpenServerDay >= actOpenDay then
        setState = true
    end

    if sendData or setState then
        SendOpenServerPKRankDataById(sysarg, nId)
    end
    
end


--开服活动发邮件奖励和公告
function OpenServerPKRankBroadMsg(nActorId, sActorName, actCfg)
    local msg
    if nId == enOpenServerRank_Leveling then
        msg = string.format(actCfg.BroadInfo, sActorName, actCfg.exparam, actCfg.param)
    elseif nId == enOpenServerRank_Swing then
        msg = string.format(actCfg.BroadInfo, sActorName, SwingEquipConfig.SwingEquipTable[actCfg.param].name)
    elseif nId == enOpenServerRank_HeroRune then
        local step,star = OpenServerPKRankGetStepData(actCfg.param, 10)   
        msg = string.format(actCfg.BroadInfo, sActorName, step, star+1)
    elseif nId == enOpenServerRank_SoulBall then
        local step,star = OpenServerPKRankGetStepData(actCfg.param, 10) 
        msg = string.format(actCfg.BroadInfo, sActorName, step+1, star+1)
    elseif nId == enOpenServerRank_SpecialRing then
        local step,star = OpenServerPKRankGetStepData(actCfg.param, 10) 
        msg = string.format(actCfg.BroadInfo, sActorName, step+1, star+1)
    elseif nId == enOpenServerRank_Wuhun then
        local step,star = OpenServerPKRankGetStepData(actCfg.param, 10) 
        msg = string.format(actCfg.BroadInfo, sActorName, step+1, star+1)
    elseif nId == enOpenServerRank_Merdian then
        local step,star = OpenServerPKRankGetStepData(actCfg.param, MeridianCfg.stepNum)    
        msg = string.format(actCfg.BroadInfo, sActorName, step+1, star+1)
    elseif nId == enOpenServerRank_Inject then  
        msg = string.format(actCfg.BroadInfo, sActorName, actCfg.param)
    elseif nId == enOpenServerRank_Diamond then
        msg = string.format(actCfg.BroadInfo, sActorName, actCfg.param)
    elseif nId == enOpenServerRank_VIP then
        msg = string.format(actCfg.BroadInfo, sActorName, actCfg.param)
    end
    System.broadcastTipmsg(msg,ttScreenCenter + ttChatWindow)
end

--神炉等级获取阶段和星级
function OpenServerPKRankGetStepData(Lv, step)
    return SeperateNumByMode( Lv - 1, step )
end

--[开服活动]通用界面数据(冲级，龙珠，兵魂，翅膀,坐骑)
--nId  活动id
function SendOpenServerPKRankDataById(sysarg, nId)
    --print("nId = "..nId)

    local actCfg = OpenServerCfg.pkRankData[nId]

    if not actCfg then
        return
    end

    local rankPtr = Ranking.getRanking(RankList[actCfg.RankId].strName)
    if not rankPtr then
        return
    end

    local nOpenServerDay = System.getDaysSinceOpenServer()

    local actOpenDay = actCfg.openDay or 1
    local actEndDay = actCfg.endDay or OpenServerCfg.OpenServerDay

    local actorid = Actor.getActorId(sysarg)
    local item = Ranking.getItemPtrFromId(rankPtr, actorid)
    local myIdx = 0
    local param = 0
    local exparam = 0
    local myState = {}

    local firstPlayerName = ""
    local firstParam = 0
    local firstExparam = 0

    local firstItem = Ranking.getItemFromIndex(rankPtr, 0)
    if firstItem then
        firstPlayerName = Ranking.getSub(firstItem, 0)
        --print("firstPlayerName ="..firstPlayerName)
        local firstScore = Ranking.getPoint(firstItem)
       -- print("firstScore ="..firstScore)
        local firstParam1 = firstScore
        local firstExparam1 = 0
        if nId == enOpenServerRank_Leveling then
            firstParam = firstScore % OpenServerCfg.OpenServerCircleRate
            firstExparam = math.floor(firstScore / OpenServerCfg.OpenServerCircleRate)
            firstParam1 = firstParam
            firstExparam1 = firstExparam
        elseif enOpenServerRank_VIP == nId then --vip特殊处理
            firstExparam = firstScore % OpenServerCfg.OpenServerVIPRate
            firstParam = math.floor(firstScore / OpenServerCfg.OpenServerVIPRate)
            firstParam1 = firstParam
            firstExparam1 = firstExparam
        elseif nId == enOpenServerRank_SoulBall or nId == enOpenServerRank_SpecialRing or nId == enOpenServerRank_Wuhun then
            local step,star = OpenServerPKRankGetStepData(firstScore, 10)  
            firstParam = step + 1
            firstExparam = star + 1  
        elseif nId == enOpenServerRank_Merdian then
            local step,star = OpenServerPKRankGetStepData(firstScore, MeridianCfg.stepNum)
            firstParam = step + 1
            firstExparam = star + 1  
        elseif nId == enOpenServerRank_HeroRune then
            local step,star = OpenServerPKRankGetStepData(firstScore, 10)  
            firstParam = step
            firstExparam = star + 1
        else
            firstParam = firstScore
        end

        if not (firstParam1 >= actCfg.param and firstExparam1 >= (actCfg.exparam or 0)) then
            firstPlayerName = ""
            firstParam = 0
            firstExparam = 0
        end
    end

    if item and nOpenServerDay >= actOpenDay then
        local myScore = Ranking.getPoint(item) 
        --print("myScore ="..myScore)
        myIdx = Ranking.getIndexFromPtr(item) + 1
        --print("myIdx1 ="..myIdx)
        local param1 = myScore
        local param2 = 0
        if nId == enOpenServerRank_Leveling then
            param = myScore % OpenServerCfg.OpenServerCircleRate
            exparam = math.floor(myScore / OpenServerCfg.OpenServerCircleRate)
            param1 = param
            param2 = exparam
        elseif enOpenServerRank_VIP == nId then --vip特殊处理
            exparam = myScore % OpenServerCfg.OpenServerVIPRate
            param = math.floor(myScore / OpenServerCfg.OpenServerVIPRate)
            param1 = param
            param2 = exparam
        elseif nId == enOpenServerRank_SoulBall or nId == enOpenServerRank_SpecialRing or nId == enOpenServerRank_Wuhun then
            local step,star = OpenServerPKRankGetStepData(myScore, 10)  
            param = step + 1
            exparam = star + 1  
        elseif nId == enOpenServerRank_Merdian then
            local step,star = OpenServerPKRankGetStepData(myScore, MeridianCfg.stepNum)
            param = step + 1
            exparam = star + 1
        elseif nId == enOpenServerRank_HeroRune then
            local step,star = OpenServerPKRankGetStepData(myScore, 10)  
            param = step
            exparam = star + 1 
        else
            param = myScore
        end

        if myIdx > actCfg.maxRankNum then
            --print("myIdx2 ="..myIdx)
            myIdx = 0
        end

        if not (param1 >= actCfg.param and param2 >= (actCfg.exparam or 0)) then
            myIdx = 0
        end

        local data = Ranking.getSub(item, 1)
        local myData = BaseFuc_unserialize(data)

        if not myData then
            myData = {}
        end

        if not myData.myAwardState then
            myData.myAwardState = {}
        end

        --print("type(myData.myAwardState) ="..type(myData.myAwardState))
        if myData.myAwardState and type(myData.myAwardState) == "number" then
            myData.myAwardState = {}
        end

        myState = myData.myAwardState
    end

    local sVarSendNum = OpenServerPKRankGetSendCount(nId)
    

    local npack = DataPack.allocPacket(sysarg,LogicCmd.miscSys.sysId, LogicCmd.miscSys.sub.sGetOpenServerPkRankData)
    if npack == nil then 
        return 
    end
    --print("nId ="..nId)
    DataPack.writeByte(npack, nId)
    if actCfg.Rewards then
        local len = #actCfg.Rewards
        DataPack.writeByte(npack, len)
        for idx = 1, len do
            local config = actCfg.Rewards[idx]
            local hadSendCount = sVarSendNum[idx] or 0
            local lastCount = config.limitNum - hadSendCount
            if config.limitNum == -1 then
                lastCount = -1 
            end
            DataPack.writeByte(npack, idx)
            if nOpenServerDay > actEndDay and myState[idx] and myState[idx] == OpenServerAwardState_Complete_No_Award then
                DataPack.writeByte(npack, OpenServerAwardState_No_Complete)
            else
                DataPack.writeByte(npack, myState[idx] or 0)
            end
            DataPack.writeInt(npack, lastCount)
        end
    else
        --print("len ="..0)
        DataPack.writeByte(npack, 0)
    end
    
    
    --print("myIdx ="..myIdx)
    DataPack.writeByte(npack, myIdx)

    --print("param ="..param)
    DataPack.writeInt(npack, param)
    --print("exparam ="..exparam)
    DataPack.writeByte(npack, exparam)
    
   -- print("firstPlayerName ="..firstPlayerName)
    DataPack.writeString(npack, firstPlayerName)
    --print("firstParam ="..firstParam)
    DataPack.writeInt(npack, firstParam)
    --print("firstExparam ="..firstExparam)
    DataPack.writeByte(npack, firstExparam)
    
    DataPack.flush(npack) 
end


--活动结束后第一天邮件第一名奖励
function OpenServerPKRankNewDayArrive()
	--[[
    if not IsInOpenServerDailyEndDay() then
        return
    end
    for idx =enOpenServerRank_Leveling, enOpenServerRank_VIP do
        local actCfg = OpenServerCfg.pkRankData[idx]
        if actCfg then
            local day = System.getDaysSinceOpenServer()
            if actCfg.endDay and actCfg.endDay + 1 == day then
                local rankPtr = Ranking.getRanking(RankList[actCfg.RankId].strName)
                if rankPtr then
                    local rankCount = Ranking.getRankItemCount(rankPtr)
                    local item = Ranking.getItemFromIndex(rankPtr, 0)
                    if item then
                        local actorId = tonumber(Ranking.getId(item))
                        local myScore = Ranking.getPoint(item) 
                        local data = Ranking.getSub(item, 1)
                        local myData = BaseFuc_unserialize(data)

                        if not myData then
                            myData = {}
                        end
                        local param1 = myScore
                        local param2 = 0
                        if idx == enOpenServerRank_Leveling then
                            param1 = myScore % OpenServerCfg.OpenServerCircleRate
                            param2 = math.floor(myScore / OpenServerCfg.OpenServerCircleRate)
                        elseif enOpenServerRank_VIP == idx then --vip特殊处理
                            param2 = myScore % OpenServerCfg.OpenServerVIPRate
                            param1 = math.floor(myScore / OpenServerCfg.OpenServerVIPRate)
                        end 

                        if param1 >= actCfg.param and param2 >= (actCfg.exparam or 0) and actCfg.exAwards then
                            local title, content = GetOpenServerPKRankMailData(idx)

                            Awards.GiveToMailById(actorId, actCfg.exAwards, title, content, 1096, Lang.LogTips.OpenServerPKRank, myData.vocation, myData.sex)
                        end
                    end
                end
            end
        end
    end
	]]
end

--第一名邮件数据
function GetOpenServerPKRankMailData(nId)
    if nId == enOpenServerRank_Leveling then
        return Lang.ScriptTips.OpenServerPKRankMail001, Lang.ScriptTips.OpenServerPKRankMail002
    elseif nId == enOpenServerRank_Swing then
        return Lang.ScriptTips.OpenServerPKRankMail003, Lang.ScriptTips.OpenServerPKRankMail004
    elseif nId == enOpenServerRank_HeroRune then
        return Lang.ScriptTips.OpenServerPKRankMail005, Lang.ScriptTips.OpenServerPKRankMail006
    elseif nId == enOpenServerRank_SoulBall then
        return Lang.ScriptTips.OpenServerPKRankMail007, Lang.ScriptTips.OpenServerPKRankMail008
    elseif nId == enOpenServerRank_SpecialRing then
        return Lang.ScriptTips.OpenServerPKRankMail009, Lang.ScriptTips.OpenServerPKRankMail010
    elseif nId == enOpenServerRank_Wuhun then
        return Lang.ScriptTips.OpenServerPKRankMail011, Lang.ScriptTips.OpenServerPKRankMail012
    elseif nId == enOpenServerRank_Merdian then
        return Lang.ScriptTips.OpenServerPKRankMail013, Lang.ScriptTips.OpenServerPKRankMail014
    elseif nId == enOpenServerRank_Inject then  
        return Lang.ScriptTips.OpenServerPKRankMail015, Lang.ScriptTips.OpenServerPKRankMail016
    elseif nId == enOpenServerRank_Diamond then
        return Lang.ScriptTips.OpenServerPKRankMail017, Lang.ScriptTips.OpenServerPKRankMail018
    elseif nId == enOpenServerRank_VIP then
        return Lang.ScriptTips.OpenServerPKRankMail019, Lang.ScriptTips.OpenServerPKRankMail020
    else
        return "", ""
    end
end


--第一名邮件数据
function GetOpenServerPKRankNormalMailData(nId)
    if nId == enOpenServerRank_Leveling then
        return Lang.ScriptTips.OpenServerPKRankNormalMail001, Lang.ScriptTips.OpenServerPKRankNormalMail002
    elseif nId == enOpenServerRank_Swing then
        return Lang.ScriptTips.OpenServerPKRankNormalMail003, Lang.ScriptTips.OpenServerPKRankNormalMail004
    elseif nId == enOpenServerRank_HeroRune then
        return Lang.ScriptTips.OpenServerPKRankNormalMail005, Lang.ScriptTips.OpenServerPKRankNormalMail006
    elseif nId == enOpenServerRank_SoulBall then
        return Lang.ScriptTips.OpenServerPKRankNormalMail007, Lang.ScriptTips.OpenServerPKRankNormalMail008
    elseif nId == enOpenServerRank_SpecialRing then
        return Lang.ScriptTips.OpenServerPKRankNormalMail009, Lang.ScriptTips.OpenServerPKRankNormalMail010
    elseif nId == enOpenServerRank_Wuhun then
        return Lang.ScriptTips.OpenServerPKRankNormalMail011, Lang.ScriptTips.OpenServerPKRankNormalMail012
    elseif nId == enOpenServerRank_Merdian then
        return Lang.ScriptTips.OpenServerPKRankNormalMail013, Lang.ScriptTips.OpenServerPKRankNormalMail014
    elseif nId == enOpenServerRank_Inject then  
        return Lang.ScriptTips.OpenServerPKRankNormalMail015, Lang.ScriptTips.OpenServerPKRankNormalMail016
    elseif nId == enOpenServerRank_Diamond then
        return Lang.ScriptTips.OpenServerPKRankNormalMail017, Lang.ScriptTips.OpenServerPKRankNormalMail018
    elseif nId == enOpenServerRank_VIP then
        return Lang.ScriptTips.OpenServerPKRankNormalMail019, Lang.ScriptTips.OpenServerPKRankNormalMail020
    else
        return "", ""
    end
end

function GetOpenServerPKRankMyRank(actorid, nId, param1, param2)
    local myIdx = 0
    local actCfg = OpenServerCfg.pkRankData[nId]
    if not actCfg then
        return myIdx
    end
    local rankPtr = Ranking.getRanking(RankList[actCfg.RankId].strName)
    if rankPtr then
        local myItem = Ranking.getItemPtrFromId(rankPtr, actorid)
        if myItem then
            myIdx = Ranking.getIndexFromPtr( myItem ) + 1
            if not (param1 >= actCfg.param and param2 >= (actCfg.exparam or 0)) then
                myIdx = 0
            elseif myIdx > actCfg.maxRankNum then
                myIdx = 0
            end
        end
    end
    return myIdx            
end


